package com.obggtc.picture.controller;

import com.obggtc.picture.common.R;
import com.obggtc.picture.dto.ai.AiChatRequest;
import com.obggtc.picture.dto.ai.AiChatResponse;
import com.obggtc.picture.service.AiService;
import com.obggtc.picture.utils.AiUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * AI控制器
 * 处理AI相关的HTTP请求
 * 
 * @author system
 * @date 2025/09/10
 */
@Slf4j
@RestController
@RequestMapping("/api/ai")
@Validated
public class AiController {
    
    @Autowired
    private AiService aiService;
    
    @Autowired
    private AiUtils aiUtils;
    
    /**
     * AI聊天接口
     * 
     * @param request 聊天请求
     * @return 聊天响应
     */
    @PostMapping("/chat")
    public R<Object> chat(@Valid @RequestBody AiChatRequest request) {
        try {
            log.info("收到AI聊天请求：{}", request.getMessage());
            
            AiChatResponse response = aiService.chat(request);
            
            if (response.getCode() == 200) {
                return R.ok(response, "AI聊天成功");
            } else {
                return R.failed(response.getCode(), response.getMessage());
            }
            
        } catch (Exception e) {
            log.error("AI聊天接口异常", e);
            return R.failed(500, "AI聊天服务异常：" + e.getMessage());
        }
    }
    
    /**
     * 检查AI服务状态
     * 
     * @return 服务状态
     */
    @GetMapping("/status")
    public R<Object> checkStatus() {
        try {
            boolean available = aiService.isServiceAvailable();
            return R.ok(available, available ? "AI服务可用" : "AI服务配置不完整");
        } catch (Exception e) {
            log.error("检查AI服务状态异常", e);
            return R.failed(500, "检查服务状态异常：" + e.getMessage());
        }
    }
    
    /**
     * 测试AI连接
     * 
     * @return 测试结果
     */
    @GetMapping("/test")
    public R<Object> testConnection() {
        try {
            boolean connected = aiUtils.testConnection();
            return R.ok(connected, connected ? "AI连接测试成功" : "AI连接测试失败");
        } catch (Exception e) {
            log.error("AI连接测试异常", e);
            return R.failed(500, "连接测试异常：" + e.getMessage());
        }
    }
    
    /**
     * 快速聊天接口（简化版）
     * 
     * @param message 消息内容
     * @return AI回复
     */
    @PostMapping("/quick-chat")
    public R<Object> quickChat(@RequestParam String message) {
        try {
            if (message == null || message.trim().isEmpty()) {
                return R.failed(400, "消息内容不能为空");
            }
            
            AiChatRequest request = new AiChatRequest();
            request.setMessage(message.trim());
            
            AiChatResponse response = aiService.chat(request);
            
            if (response.getCode() == 200) {
                return R.ok(response.getContent(), "AI回复成功");
            } else {
                return R.failed(response.getCode(), response.getMessage());
            }
            
        } catch (Exception e) {
            log.error("快速聊天接口异常", e);
            return R.failed(500, "快速聊天异常：" + e.getMessage());
        }
    }
    
    /**
     * 使用指定AI提供商聊天
     * 
     * @param request 聊天请求
     * @param provider AI提供商代码 (tencent, kimi, doubao, aliyun)
     * @return 聊天响应
     */
    @PostMapping("/chat/{provider}")
    public R<Object> chatWithProvider(@Valid @RequestBody AiChatRequest request, 
                                     @PathVariable String provider) {
        try {
            log.info("收到指定提供商AI聊天请求，提供商：{}，消息：{}", provider, request.getMessage());
            
            AiChatResponse response = aiService.chat(request, provider);
            
            if (response.getCode() == 200) {
                return R.ok(response, "AI聊天成功");
            } else {
                return R.failed(response.getCode(), response.getMessage());
            }
            
        } catch (Exception e) {
            log.error("指定提供商AI聊天接口异常", e);
            return R.failed(500, "AI聊天服务异常：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有AI提供商状态
     * 
     * @return 提供商状态列表
     */
    @GetMapping("/providers/status")
    public R<Object> getProvidersStatus() {
        try {
            Map<String, Boolean> statusMap = aiService.getAllProvidersStatus();
            return R.ok(statusMap, "获取提供商状态成功");
        } catch (Exception e) {
            log.error("获取提供商状态异常", e);
            return R.failed(500, "获取提供商状态异常：" + e.getMessage());
        }
    }
    
    /**
     * 测试指定AI提供商连接
     * 
     * @param provider AI提供商代码
     * @return 测试结果
     */
    @GetMapping("/test/{provider}")
    public R<Object> testProviderConnection(@PathVariable String provider) {
        try {
            boolean connected = aiService.testConnection(provider);
            return R.ok(connected, connected ? 
                provider + " AI连接测试成功" : provider + " AI连接测试失败");
        } catch (Exception e) {
            log.error("{}AI连接测试异常", provider, e);
            return R.failed(500, provider + "连接测试异常：" + e.getMessage());
        }
    }
}
